// src/routes/tbots/+page.ts
import type { PageLoad } from './$types';
import * as commands from '$lib/commands';

import type { IpcResponse, ListParams, TradeBot, TradeBotFilter } from '$lib/bindings';

export const load: PageLoad = async ({ fetch, params, url }) => {
    const currentPage = parseInt(url.searchParams.get('page') || '1', 10) - 1; // Get the page parameter from the URL query

    console.log(`currentPage = ${currentPage} `)

    try {
        // Define the argument
        const args: ListParams<TradeBotFilter> = {
            page: currentPage,
            size: 100,
            filter: null,
        }

        const res: IpcResponse<TradeBot[]> = await commands.list_trade_bots(args)

        if (res.error) {
            // If the response status is not OK, throw an error
            throw new Error(`(tbots/+page.ts)Server returned an error: ${res.error}`);
        }

        console.log("(tbots/+page.ts) list_trade_bots.res=", res);

        // If the server response is empty, return sample data
        if (res.result) {
            return {
                currentPage: currentPage,
                tbots: res.result.data,
            };
        }

        return {
            currentPage: currentPage,
            tbots: [],
        };
    } catch (error) {
        // If there's any error (e.g., network issue), return sample data
        console.error('Error fetching tbots:', error);
        return {
            currentPage: currentPage,
            tbots: [],
        };
    }
};